package com.swak.reactivex.threads.waitstrategy;

import java.util.concurrent.TimeoutException;

import com.swak.reactivex.threads.Barrier;
import com.swak.reactivex.threads.WaitStrategy;

/**
 * CPU 占用率 15% 左右, 非常的耗系统的信息
 * 
 * @author 618lf
 */
public class YieldingWaitStrategy implements WaitStrategy {

	private static final int SPIN_TRIES = 100;

	@Override
	public void waitFor(Barrier barrier) throws InterruptedException, TimeoutException {
		int counter = SPIN_TRIES;

		while (!this.checkBarrier(barrier)) {
			counter = applyWaitMethod(counter);
		}
	}

	@Override
	public void wakeup() {

	}

	private int applyWaitMethod(int counter) {
		if (0 == counter) {
			Thread.yield();
		} else {
			--counter;
		}
		return counter;
	}

}
